import Taro, { Component } from '@tarojs/taro'
import { View, Image, Text, Input } from '@tarojs/components'
import { AtSearchBar, AtSwipeAction } from 'taro-ui'
import { DNavBar, Ddialog } from '@/components'
import http from '@/api'
import './index.scss'
import QRCode from 'qrcode'
const conf = require('../../../../config/conf')

// 邀请链接baseURL
const baseURL = conf.baseURL

export default class EnterpriseMember extends Component {
    state = {
        photo: require('../../../assets/images/photo.png'),
        warnIcon: require('../../../assets/images/icon／基础／09error@2x.png'),
        closeIcon: require('../../../assets/images/icon／关闭@2x.png'),
        showInviteDialog: false,
        employeeList: '',
        searchVal: '',
        options: [
            {
                text: '删除',
                style: {
                    backgroundColor: '#ff585b'
                }
            }
        ],
        adminList: '',
        showDialog: false,
        delId: '', // 删除员工ID
        userInfo: '',
        entInfo: ''
    }

    componentDidMount() {
        this.getUserInfo()
        this.getEntInfo()
    }

    createLink() {
        // 生成邀请链接
        let { userInfo, entInfo } = this.state
        let link = encodeURI(`${baseURL}#/pages/myEnterprise/joinEnterprise?entId=${userInfo.entId}&imName=${userInfo.imName}&entName=${entInfo.entName}&manager=${entInfo.entOwner}`)
        this.refs.likeDom.value = link

        QRCode.toCanvas(document.getElementById('canvas'), link, {
            width: 160,
            height: 160
        }, function (error) {
            if (error) throw new Error(error)
        })
    }

    copyLink() {
        this.refs.likeDom.select()
        document.execCommand('copy')
        Taro.showToast({
            title: '复制成功',
            icon: 'none'
        })
    }

    handleRightText = () => {
        this.setState({
            showInviteDialog: true
        }, () => {
            this.createLink()
        })
    }

    onActionClick = () => {
        const { userInfo } = this.state
        this.searchEmployeeList({
            entId: userInfo.entId,
            imName: this.state.searchVal
        })
    }

    async getUserInfo() {
        const userInfo = await http.myselfDetail()
        this.setState({
            userInfo
        })
        this.searchEmployeeList({ entId: userInfo.entId })
    }
    async getEntInfo() {
        let entInfo = await http.getEntinfo()
        this.setState({
            entInfo
        })
    }

    async searchEmployeeList(params) {
        const list = await http.searchEmployeeList(params)
        let employeeList = []
        let adminList = []

        list.forEach(item => {
            if (item.imIdStatus == 1) {
                // 管理员
                let index = adminList.findIndex(item => item.title == '管理员')
                if (index === -1) {
                    adminList.push({
                        title: '管理员',
                        children: [{
                            ...item
                        }]
                    })
                } else {
                    adminList[index].children.push({ ...item })
                }
            } else {
                // 普通员工
                let index = employeeList.findIndex(item => item.title == item.firstPinYin)
                if (index === -1) {
                    employeeList.push({
                        title: item.firstPinYin,
                        children: [{
                            ...item
                        }]
                    })
                } else {
                    employeeList[index].children.push({ ...item })
                }
            }
        })
        this.setState({
            employeeList,
            adminList
        })
    }

    changeSearchVal(searchVal) {
        const { userInfo } =this.state
        if (searchVal == '') {
            this.searchEmployeeList({ entId: userInfo.entId })
        }
        this.setState({
            searchVal
        })
    }

    handleClick = (delId) => {
        this.setState({
            showDialog: true,
            delId
        })
    }

    // 确认删除
    async onSure() {
        const { delId, userInfo } = this.state
        await http.removeEmployee({ myId: delId, entName: userInfo.entName })
        this.searchEmployeeList({ entId: userInfo.entId })

        this.setState({
            showDialog: false,
            delId: ''
        })
    }

    render() {
        const { photo, options, warnIcon, closeIcon, showInviteDialog, employeeList, searchVal, showDialog, adminList, userInfo } = this.state

        return (
            <View className="enterprise_member">
                <DNavBar title="企业员工"></DNavBar>


                <View className="container">
                    <AtSearchBar value={searchVal} onActionClick={this.onActionClick} onChange={this.changeSearchVal.bind(this)}></AtSearchBar>

                    <View className="member_body">
                        {
                            // 管理员列表
                            adminList && adminList.map(item => <View className="member_body_item">
                                <View className="member_body_item_title title">
                                    <View>超管、{item.title}（{item.children.length}人）</View>
                                    <View className="rightText" onClick={this.handleRightText}>生成邀请码</View>
                                </View>

                                {
                                    item.children && item.children.map(item1 => <View className="member_body_item_children">
                                        <AtSwipeAction
                                            options={options}
                                            onClick={this.handleClick.bind(this, item1.id)}
                                            disabled
                                        >
                                            <View className='normal'>
                                                <Image src={item1.imPicUrl} onError={(event) => {
                                                    event.target.src = photo
                                                }} className="photo"></Image>
                                                <View className="info">
                                                    <View className="info_name_tag">
                                                        <Text className="name">{item1.imName}</Text>
                                                        <Text className="tag">超级管理员</Text>
                                                    </View>
                                                    <View className="info_job">{item1.post ? item1.post : '---'}</View>
                                                    {
                                                        userInfo.id == item1.id && <View className="me">我</View>
                                                    }
                                                </View>
                                            </View>
                                        </AtSwipeAction>
                                    </View>)
                                }
                            </View>)
                        }

                        {
                            // 员工列表
                            employeeList && employeeList.map(item => <View className="member_body_item">
                                <View className="member_body_item_title">{item.title}（{item.children.length}人）</View>

                                {
                                    item.children && item.children.map(item1 => <View className="member_body_item_children">
                                        <AtSwipeAction
                                            options={options}
                                            onClick={this.handleClick.bind(this, item1.id)}
                                            disabled={userInfo.imIdStatus != 1}
                                        >
                                            <View className='normal'>
                                                <Image src={item1.imPicUrl} onError={(event) => {
                                                    event.target.src = photo
                                                }} className="photo"></Image>
                                                <View className="info">
                                                    <View className="info_name_tag">
                                                        <Text className="name">{item1.imName}</Text>
                                                        {

                                                            (item1.authStatus == 0 || item1.authStatus == 3) && <Text className="warn">
                                                                <Image src={warnIcon} className="warn_icon"></Image>
                                                                 待个人认证
                                                            </Text>
                                                        }
                                                    </View>
                                                    <View className="info_job">{item1.post ? item1.post : '---'}</View>
                                                    {
                                                        userInfo.id == item1.id && <View className="me">我</View>
                                                    }
                                                </View>
                                            </View>
                                        </AtSwipeAction>
                                    </View>)
                                }
                            </View>)
                        }
                        {
                            employeeList && !employeeList.length && !adminList.length && <View className="no_employee">没有该用户</View>
                        }
                    </View>
                </View>

                {
                    showInviteDialog && <View className="invite_dialog">
                        <View className="invite_dialog_body">
                            <View className="invite_dialog_body_content">
                                <View className="title">邀请同事</View>
                                <View className="con">
                                    <View className="con_title">分享二维码通知加入</View>
                                    <View className="con_text">成员扫码后快速加入企业</View>
                                    <canvas className="qrCode" id="canvas"></canvas>
                                    <View className="copy_like" onClick={this.copyLink.bind(this)}>复制邀请链接</View>
                                </View>
                            </View>
                            <View className="invite_dialog_body_close" onClick={() => {
                                this.setState({
                                    showInviteDialog: false
                                })
                            }}>
                                <Image src={closeIcon} className="closeIcon"></Image>
                            </View>
                            <input type="text" ref="likeDom" style={{ opacity: 0, marginTop: '100px' }} />
                        </View>
                    </View>
                }

                <Ddialog isShow={showDialog} content="是否确认删除" onCancel={() => {
                    this.setState({ showDialog: false })
                }} onSure={this.onSure.bind(this)}></Ddialog>
            </View>
        )
    }
}
